
import 'package:flutter/material.dart';

// 简介详情展开控件
class ExpandableText extends StatefulWidget {
  final String text;
  final int maxLines;
  final TextStyle style;
  final bool expand;
  final bool hasBorder;
  final double marginTop;
  final String unfoldWord;
  final String foldWord;

  // 收起 展开的样式
  final TextStyle textStyle;
 
  const ExpandableText({Key key, this.text, this.maxLines, this.style, this.expand, this.hasBorder = true, this.marginTop = 14, this.textStyle = const TextStyle(
    color:Color(0xFF82868E),
    fontSize:12,
    fontWeight: FontWeight.w500,
    height: 1.5
  ), this.unfoldWord = '展开', this.foldWord = '收起', }) : super(key: key);
 
  @override
  State<StatefulWidget> createState() {
    return _ExpandableTextState(text, maxLines, style, expand);
  }
 
}
 
class _ExpandableTextState extends State<ExpandableText> {
  final String text;
  final int maxLines;
  final TextStyle style;
  bool expand;
 
  _ExpandableTextState(this.text, this.maxLines, this.style, this.expand) {
    if (expand == null) {
      expand = false;
    }
  }
 
  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(builder: (context, size) {
      final span = TextSpan(text: text ?? '', style: style);
      final tp = TextPainter(
          text: span, maxLines: maxLines, textDirection: TextDirection.ltr);
      tp.layout(maxWidth: size.maxWidth);
 
      if (tp.didExceedMaxLines) {
        return Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            expand ?
            Text(text ?? '', style: style) :
            Text(text ?? '', maxLines: maxLines,
                overflow: TextOverflow.ellipsis,
                style: style),
            
            GestureDetector(
              behavior: HitTestBehavior.translucent,
              onTap: () {
                setState(() {
                  expand = !expand;
                });
              },
              child: Container(
                padding: EdgeInsets.only(top: widget.marginTop),
                child: expand ? _renderBtn(widget.foldWord) : _renderBtn(widget.unfoldWord),
              ),
            ),
          ],
        );
      } else {
        return Text(text ?? '', style: style);
      }
    });
  }
  _renderBtn(text){
    return Container(
      padding: widget.hasBorder ? const EdgeInsets.fromLTRB(6.5,0,6.6,0) : const EdgeInsets.all(0),
      decoration: widget.hasBorder ?  BoxDecoration(
        borderRadius: BorderRadius.all(Radius.circular(2.5)),
        border: Border.all(color: Color(0xFF82868E),width: 0.5)
      ) : null,
      child: Text(
        text,
        style: widget.textStyle,
      ),
    );
  }
}